package org.speed.httpclient;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.util.EntityUtils;

public class TestHttpClient {

	
	public static void main(String[] args) throws Exception {
		
		
		//abs();
		
		CloseableHttpClient httpclient = HttpClients.createDefault();  
		HttpGet httpget = new HttpGet("http://www.baidu.com");  
		CloseableHttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		String res = EntityUtils.toString(entity);
		System.out.println(res);
		
		response.close();
	}

	private static void abs() throws IOReactorException, UnsupportedEncodingException {
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(5000)
				.setSocketTimeout(5000)
				.setConnectionRequestTimeout(2000)
				.build();
		
		
		IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
				setIoThreadCount(1)
				.setBacklogSize(1)
				.setSoKeepAlive(true)
				.build();
		
		ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
		PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
		connManager.setMaxTotal(1);
		connManager.setDefaultMaxPerRoute(1);
		CloseableHttpAsyncClient client = HttpAsyncClients.custom().
				setConnectionManager(connManager)
				.setDefaultRequestConfig(requestConfig)
				.build();
		
		HttpPost httpPost = new HttpPost("http://www.yyb.com");
		StringEntity entity = new StringEntity("");
		httpPost.setEntity(entity);
		
		
		client.start();
		
		
		while(true) {
			
			client.execute(httpPost, new FutureCallback<HttpResponse>() {
				
				@Override
				public void failed(Exception ex) {
					System.out.println("failed");
					
				}
				
				@Override
				public void completed(HttpResponse result) {
					System.out.println("completed");
					
				}
				
				@Override
				public void cancelled() {
					System.out.println("cancelled");
				}
			});
			
		}
	}
	
	
}
